class_name Player extends Tank

var player_shell_tscn := preload("res://entity/bullet/player_shell.tscn")

##控制器ID
@export var device: String = ""  #设备KEY  key_  |  joy0_  joy1_  joy2_
##角色ID
@export var charactor_id: int = -1

## 触摸屏移动方向
var touch_vector: Vector2 = Vector2.ZERO

@onready var fire_rate_timer: Timer = $FireRateTimer

@export var peer_id := 1 :
	set(id):
		peer_id = id
		$PlayerInput.set_multiplayer_authority(id)

@onready var multiplayer_synchronizer: MultiplayerSynchronizer = $MultiplayerSynchronizer
@onready var shell_pos: Marker2D = $Graphics/Diff/Pao/ShellPos
@onready var animation_player: AnimationPlayer = $AnimationPlayer
@onready var player_input: MultiplayerSynchronizer = $PlayerInput
@onready var state_machine: StateMachine = $StateMachine

## 状态机
enum State{
	IDLE,
	MOVE,
}


func tick_physics(state: int, _delta: float) -> void:
	match state:
		State.MOVE:
			move()


func get_next_state(last_state: int) -> int:
	match last_state:
		State.IDLE:
			if player_input.dir.length():
				return State.MOVE
		State.MOVE:
			if not player_input.dir.length():
				return State.IDLE
			
	return StateMachine.KEEP_CURRENT


func transition_state(_from: int, to: int) -> void:
	match to:
		State.IDLE:
			animation_player.stop()
		State.MOVE:
			animation_player.play("move")



func make_fire() -> void:
	fire.rpc(shell_pos.global_position, Vector2.ZERO, rotation)
	fire_rate_timer.start()


@rpc("any_peer", "call_local")
func fire(pos: Vector2, sca: Vector2, rot: float) -> void:
	var ob := player_shell_tscn.instantiate()
	ob.speed = shell_speed
	ob.damage = damage
	ob.shooter = self
	Global.add_scene(ob, pos, sca, rot, Game.main.get_node("World/Objects/Bullets"))


func move() -> void:
	if player_input.dir.length():
		rotation = player_input.dir.angle()
	velocity = speed * player_input.dir
	move_and_slide()


func die() -> void:
	queue_free()


func hurt(from: Node2D) -> void:
	if "damage" in from:
		health -= from.damage
		if health <= 0: die()
	SignalManager.player_update.emit()


## 获取buff
func get_buff(bf: Buff) -> void:
	if bf.health > 0: 
		health = max_health if health >= max_health else (bf.health + health)
	if bf.max_health > 0: max_health += bf.max_health
	if bf.damage > 0: damage += bf.damage
	if bf.speed > 0: speed += bf.speed
	if bf.fire_rate > 0: 
		fire_rate += bf.fire_rate
		fire_rate_timer.wait_time = 1.0/fire_rate
	if bf.shell_speed > 0: shell_speed += bf.shell_speed
	if bf.boat: 
		boat = bf.boat
		$Graphics/Boat.visible = bf.boat
		set_collision_mask_value(Layer.PHYSICS_2D_WATER, not bf.boat)
	SignalManager.player_update.emit()




